package com.zhida.smartcontrol.pagectrl.lampmanager.editlamp;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.recycler.OnItemClick;
import com.jay.tools.ui.ButtonStyle;
import com.jay.tools.ui.TopBarView;
import com.jay.tools.utils.EventBusUtils;
import com.jay.tools.utils.SoftInputUtils;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.common.Api;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.common.PhotoDialogFragment;
import com.zhida.smartcontrol.common.PhotoOkEvent;
import com.zhida.smartcontrol.common.bean.DeviceClassifyBean;
import com.zhida.smartcontrol.common.bean.LampBean;
import com.zhida.smartcontrol.common.bean.LampSwitchBean;
import com.zhida.smartcontrol.common.mapsel.MapSelFragment;
import com.zhida.smartcontrol.dialog.OkDialogFragment;
import com.zhida.smartcontrol.mvp.MVPBaseFragment;
import com.zhida.smartcontrol.pagectrl.lampmanager.EditLampOkEvent;
import com.zhida.smartcontrol.pagehome.scan.ScanFragment;
import com.zhida.smartcontrol.pagehome.scan.ScanResultEvent;
import com.zhida.smartcontrol.pop.DeviceClassifyPop;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: tanjianpei
 * date: 2019/12/11 011 9:34
 * description: 添加或编辑单双灯
 */
public class EditLampFragment extends MVPBaseFragment<EditLampContract.View, EditLampPresenter> implements EditLampContract.View {
    @BindView(R.id.top)
    TopBarView mTopBar;
    @BindView(R.id.tv_jkq_address)
    TextView mTvJkqAddress;
    @BindView(R.id.et_device_name)
    EditText mEtDeviceName;
    @BindView(R.id.et_imei)
    EditText mEtImei;
    @BindView(R.id.et_device_num)
    EditText mEtDeviceNum;
    @BindView(R.id.et_card)
    EditText mEtCard;
    @BindView(R.id.et_factory)
    EditText mEtFactory;
    @BindView(R.id.et_lng)
    EditText mEtLng; //经度
    @BindView(R.id.et_lat)
    EditText mEtLat; // 纬度
    @BindView(R.id.et_address)
    EditText mEtAddress;
    @BindView(R.id.iv_pic)
    ImageView mIvPic;
    @BindView(R.id.btn_save)
    ButtonStyle mBtnSave;
    @BindView(R.id.tv_switch_type)
    TextView mTvSwitchType;

    private int mType;
    private String mId;
    private String mLat, mLng;
    private String mSwitchType;
    private DeviceClassifyPop mPop;
    private String mFilePath;

    private LampBean mBean;
    private LampSwitchBean mSwitchBean;

    private String mPicUrl;
    private boolean mLoadOk;
    private int mClickType;

    public static EditLampFragment newInstance(int type, LampBean bean, LampSwitchBean switchBean) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        args.putParcelable("bean", bean);
        args.putParcelable("sbean", switchBean);
        EditLampFragment fragment = new EditLampFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected Object getLayout() {
        return R.layout.fragment_edit_lamp;
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {
        inflateTopBar(mTopBar);
        Bundle bundle = getArguments();
        if (null == bundle) {
            return;
        }
        mBean = bundle.getParcelable("bean");

        if (null != mBean) {
            mTvJkqAddress.setText(mBean.getAddress());
        }

        mType = bundle.getInt("type");
        if (mType == Const.TYPE_EDIT) {
            mSwitchBean = bundle.getParcelable("sbean");
            fillEdit(mSwitchBean);
            mId = mSwitchBean.getId();
            mBtnSave.setText("修改");
            mTopBar.setTitle("编辑单灯控制器");
        } else {
            mBtnSave.setText("保存");
            mTopBar.setTitle("添加单灯控制器");
        }
        mPop = new DeviceClassifyPop(getProxyActivity(), Const.O_SINGLE);
        EventBusUtils.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    private void fillEdit(LampSwitchBean bean) {
        if (null == bean) {
            return;
        }
        mEtDeviceName.setText(bean.getName());
        mEtImei.setText(bean.getImei());
        mEtDeviceNum.setText(bean.getEquipmentCode());
        mEtCard.setText(bean.getNum() + "");
        mEtFactory.setText(bean.getManufacturer());
        mEtAddress.setText(bean.getAddress());
        mLat = bean.getLat();
        mLng = bean.getLng();
        mEtLat.setText(mLat);
        mEtLng.setText(mLng);
        mSwitchType = bean.getSwitchType();
        mTvSwitchType.setText(bean.getSwitchTypeTxt());

        mPicUrl = bean.getDevicePic();
        loadPic();
    }

    private void loadPic() {
        if (!TextUtils.isEmpty(mPicUrl))
            Glide.with(getProxyActivity())
                    .load(Api.PIC + mPicUrl)
                    .apply(new RequestOptions()
                            .placeholder(R.drawable.progress_round)
                            .error(R.drawable.ic_photo))
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            mLoadOk = false;
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            mLoadOk = true;
                            return false;
                        }
                    })
                    .into(mIvPic);
    }

    @Override
    protected void initLazyEvents() {
        mPop.setClickListener(new OnItemClick<Object>() {
            @Override
            public void onClick(Object info, int tag) {
                DeviceClassifyBean bean = (DeviceClassifyBean) info;
                mSwitchType = bean.getId();
                mTvSwitchType.setText(bean.getName());
            }
        });
    }

    @OnClick({R.id.ll_device_type, R.id.ll_jwd, R.id.btn_save, R.id.btn_reset, R.id.iv_pic,
            R.id.tv_take, R.id.fl_sao_1, R.id.fl_sao_2})
    public void click(View v) {
        SoftInputUtils.hideSoftInput(getProxyActivity());
        switch (v.getId()) {
            case R.id.ll_jwd:
                requestLocation();
                break;
            case R.id.ll_device_type: //选择类别
                mPop.showAsDropDown(mTvSwitchType, 0, 0);
                break;
            case R.id.iv_pic:
                if (mLoadOk) {

                } else {
                    loadPic();
                }
                break;
            case R.id.tv_take:
                mClickType = 1;
                requestCameraPermission();
                break;
            case R.id.fl_sao_1:
            case R.id.fl_sao_2:
                mClickType = 2;
                requestCameraPermission();
                break;
            case R.id.btn_save:
                String address = mEtAddress.getText().toString().trim();
                String equipmentCode = mEtDeviceNum.getText().toString().trim();
                String imei = mEtImei.getText().toString().trim();
                String manufacturer = mEtFactory.getText().toString().trim();
                String name = mEtDeviceName.getText().toString().trim();
                String num = mEtCard.getText().toString().trim();
                String code = "";
                String pid = "";
                if (null != mBean) {
                    code = mBean.getCode();
                    pid = mBean.getId();
                }
                mPresenter.check(mType, code, pid, address, equipmentCode, imei, mLat, mLng, manufacturer, name, num, mSwitchType, mFilePath, mId);
                break;
            case R.id.btn_reset:
                resetInput();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanResult(ScanResultEvent event) {
        mEtImei.setText(event.getImei());
        mEtDeviceNum.setText(event.getCardNo());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void photoOk(PhotoOkEvent event) {
        mFilePath = event.getPath();
        Glide.with(getProxyActivity())
                .load(mFilePath)
                .apply(new RequestOptions()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(mIvPic);
        mLoadOk = true;
    }

    @Override
    protected void openCamera() {
        switch (mClickType) {
            case 1:
                PhotoDialogFragment.newInstance().showDialog(getChildFragmentManager());
                break;
            case 2:
                start(ScanFragment.newInstance(true));
                break;
        }
    }


    private void resetInput() {
        if (mType == Const.TYPE_EDIT) {
            fillEdit(mSwitchBean);
        } else {
            mEtDeviceName.setText("");
            mEtImei.setText("");
            mEtDeviceNum.setText("");
            mEtCard.setText("");
            mEtFactory.setText("");
            mEtAddress.setText("");
            mLat = "";
            mLng = "";
            mEtLat.setText(mLat);
            mEtLng.setText(mLng);
            mSwitchType = "";
            mTvSwitchType.setText("");
        }
    }

    @Override
    protected void location(boolean hasLocation) {
        startForResult(MapSelFragment.newInstance(), 0);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 0 && null != data) {
            mLat = data.getString("lat");
            mLng = data.getString("lng");
            mEtLat.setText(mLat);
            mEtLng.setText(mLng);
        }
    }

    @Override
    public void onSuccess(String msg) {
        OkDialogFragment fragment = OkDialogFragment.newInstance(msg);
        fragment.showDialog(getChildFragmentManager());
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {
                EventBusUtils.post(new EditLampOkEvent());
                pop();
            }
        });
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        stateBar(true);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        stateBar(false);
    }


}
